package com.atguigu.tingshu.album.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.album.mapper.*;
import com.atguigu.tingshu.album.service.BaseCategoryService;
import com.atguigu.tingshu.model.album.BaseAttribute;
import com.atguigu.tingshu.model.album.BaseCategory1;
import com.atguigu.tingshu.model.album.BaseCategoryView;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@SuppressWarnings({"all"})
public class BaseCategoryServiceImpl extends ServiceImpl<BaseCategory1Mapper, BaseCategory1> implements BaseCategoryService {

	@Autowired
	private BaseCategory1Mapper baseCategory1Mapper;

	@Autowired
	private BaseCategory2Mapper baseCategory2Mapper;

	@Autowired
	private BaseCategory3Mapper baseCategory3Mapper;


	@Autowired
	private BaseCategoryViewMapper baseCategoryViewMapper;

	@Autowired
	private BaseAttributeMapper baseAttributeMapper;


	@Override
	public List<JSONObject> getBaseCategoryList() {
		//声明一个集合
		List<JSONObject> list = new ArrayList<>();
		//获取全部数据
		List<BaseCategoryView> baseCategoryViewList = baseCategoryViewMapper.selectList(null);
		Map<Long, List<BaseCategoryView>> map = baseCategoryViewList.stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory1Id));
		map.entrySet().forEach(entry -> {
			JSONObject category1 = new JSONObject();
										//获取数据:
			category1.put("categoryId", entry.getKey());
										//获取一级分类名称
			category1.put("categoryName", entry.getValue().get(0).getCategory1Name());
			//获取二级分类数据
			Map<Long, List<BaseCategoryView>> map2 = entry.getValue().stream().collect(Collectors.groupingBy(BaseCategoryView::getCategory2Id));
			ArrayList<JSONObject> category2ChildList = new ArrayList<>();
			map2.entrySet().forEach(entry2 -> {
				JSONObject category2 = new JSONObject();
				category2.put("categoryId", entry2.getKey());
				category2.put("categoryName", entry2.getValue().get(0).getCategory2Name());
				category2.put("categoryChild", entry2.getValue().stream().map(baseCategoryView -> {
					JSONObject category3 = new JSONObject();
					category3.put("categoryId", baseCategoryView.getCategory3Id());
					category3.put("categoryName", baseCategoryView.getCategory3Name());
					return category3;
				}).collect(Collectors.toList()));
				//将二级分类对象添加到集合中
				category2ChildList.add(category2);
			});
			category1.put("categoryChild", category2ChildList);
			list.add(category1);
		});
		return list;
	}
}
